package common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;


public class HtmlFormatter extends Formatter
{
	public String format(LogRecord rec)
	{
		StringBuffer buf = new StringBuffer(1000);

		int level = rec.getLevel().intValue();
		String bgColor = (level == Level.SEVERE.intValue())? "#FF0000":((level == Level.WARNING.intValue())? "#FFFF00":"#FFFFFF");
		
		buf.append("<tr bgColor="+bgColor+">");
		
		buf.append("<td WIDTH=\"5%\">");
		buf.append(rec.getLevel());
		buf.append("</td>");
		
		buf.append("<td WIDTH=\"10%\">");
		buf.append(calcDate(rec.getMillis()));
		buf.append("</td>");
		
		buf.append("<td WIDTH=\"85%\">");
		buf.append(formatMessage(rec));
		Throwable ex = rec.getThrown();

		buf.append('\n');
		buf.append("</td>");
		
		buf.append("</tr>\n");
		if (ex != null) {
			buf.append("<tr bgColor=#FF0000>");
			
			buf.append("<td WIDTH=\"5%\">");
			buf.append("</td>");
			
			buf.append("<td WIDTH=\"10%\">");
			buf.append("</td>");
			
			buf.append("<td WIDTH=\"85%\">");
			StackTraceElement[] ste = ex.getStackTrace();
			buf.append("<b>").append(ex.toString()).append("</b><br>");
			for (int i=0; i < ste.length; i++)
			  buf.append("   at ").append(ex.getStackTrace()[i]).append("<br>");

			buf.append("</td>");
			buf.append("</tr>\n");
		}	
		return buf.toString();
	}

	private String calcDate(long millisecs)
	{
		SimpleDateFormat date_format = new SimpleDateFormat("dd MMM yyyy - HH:mm");
		Date resultdate = new Date(millisecs);
		return date_format.format(resultdate);
	}

	public String getHead(Handler h)
	{
		return "<HTML>\n<HEAD>\n" + (new Date()) + "\n</HEAD>\n<BODY>\n<PRE>\n"
				+ "<table border=5>\n  "
				+ "<tr><th>Level</th><th>Time</th><th>Log Message</th></tr>\n";
	}

	public String getTail(Handler h)
	{
		return "</table>\n  </PRE></BODY>\n</HTML>\n";
	}
}